package cn.tedu._05mvcboot03.controller;


import cn.tedu._05mvcboot03.common.response.JsonResult;
import cn.tedu._05mvcboot03.common.response.StatusCode;
import cn.tedu._05mvcboot03.mapper.Mvc_userMapper;
import cn.tedu._05mvcboot03.pojo.dto.UserArticleDTO;
import cn.tedu._05mvcboot03.pojo.dto.UserLoginDTO;
import cn.tedu._05mvcboot03.pojo.entity.Mvc_article;
import cn.tedu._05mvcboot03.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;

@Api(tags = "01.用户模块")
@Slf4j
@RestController
@RequestMapping("/v1/users")
public class Mvc_userController {

    @Autowired
    private Mvc_userMapper mvc_userMapper;

    @ApiOperation(value = "登录功能")
    @PostMapping("login")
    public JsonResult login(@RequestBody UserLoginDTO userLoginDTO, @ApiIgnore HttpSession httpSession){
        log.debug("userLoginDTO = " + userLoginDTO);
        String username = userLoginDTO.getUsername();
        String password = userLoginDTO.getPassword();
        UserVO userVO = mvc_userMapper.selectByName(username,password);
        if(userVO == null){
            return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
        }
        else {
            httpSession.setAttribute("user", userVO);
            return JsonResult.ok(userVO);
        }
    }

    @ApiOperation(value = "发表文章功能")
    @PostMapping("article")
    public JsonResult article(@RequestBody @Validated UserArticleDTO userArticleDTO, @ApiIgnore HttpSession httpSession){
        log.debug("userArticleDTO = " + userArticleDTO);
        UserVO userVO = (UserVO) httpSession.getAttribute("user");
        if(userVO == null){
            return new JsonResult(StatusCode.NOT_LOGIN);
        }
        Mvc_article article = new Mvc_article();
        BeanUtils.copyProperties(userArticleDTO,article);
        article.setId(userVO.getId());
        return JsonResult.ok();
    }

}
